<?php
/**
 * Created by PhpStorm.
 * User: yyq
 * Date: 2018/9/26
 * Time: 11:21
 */

namespace Web\Controller;


use Common\Model\AddressModel;
use Common\Model\AttrDetailModel;
use Common\Model\CartModel;
use Common\Model\OrderModel;
use Common\Model\OrderProductModel;
use Common\Model\ProAttrModel;
use Common\Model\ProductModel;
use Common\Model\ProOptionModel;
use Common\Model\SaleMemberModel;

class CartController extends WebbaseController
{
    private $product_model;
    private $pro_attr_model;
    private $cart_model;
    private $attr_detail_model;
    private $pro_option_model;
    private $member_info;
    private $address_model;
    private $order_model;
    private $order_product_model;
    private $sale_member_model;

    public function __construct()
    {
        parent::__construct();
        $this->product_model    = new ProductModel();
        $this->pro_attr_model   = new ProAttrModel();
        $this->attr_detail_model= new AttrDetailModel();
        $this->pro_option_model = new ProOptionModel();
        $this->cart_model       = new CartModel();
        $this->address_model    = new AddressModel();
        $this->order_model      = new OrderModel();
        $this->order_product_model  = new OrderProductModel();
        $this->sale_member_model    = new SaleMemberModel();
        $this->member_info      = $_SESSION['member_info'];
    }

    public function addCart() {
        if(!$this->member_info['mid']) {
            exit($this->returnApiError(WebbaseController::FATAL_ERROR, '请登录'));
        }
        $pro_id     = I('post.pro_id');
        $option_id  = I('post.option_id');
//        $quantity   = I('post.quantity');
        $this->checkparam(array($pro_id, $quantity, $option_id));

//        $this->checkisNumber(array($quantity));

        $result = $this->product_model->find($pro_id);
        if (!$result) {
            exit($this->returnApiError(WebbaseController::FATAL_ERROR, '商品不存在'));
        }

        if ($result['status'] == ProductModel::STATUS_DOWN) {
            exit($this->returnApiError(WebbaseController::FATAL_ERROR, '该商品已下架'));
        }
        $option_info = $this->pro_option_model->find($option_id);
        if(!$option_info['stock']) {
            exit($this->returnApiError(WebbaseController::FATAL_ERROR, '库存不足'));
        }
        $cart = $this->cart_model->where(['pro_id' => $pro_id, 'mid' => $this->member_info['mid'], 'option_id' => $option_id])->find();
        if($cart) {
            exit($this->returnApiError(WebbaseController::FATAL_ERROR, '该商品已在购物车中'));
        }
        if($result['if_online'] == 'yes') {
            if($this->cart_model->where(['pro_id' => $pro_id, 'mid' => $this->member_info['mid']])->find()) {
                exit($this->returnApiError(WebbaseController::FATAL_ERROR, '在线选号商品只能购买一件'));
            }
        }

        $member_info = $_SESSION['member_info'];
        $data = array(
            'mid'           => $this->member_info['mid'],
            'pro_id'        => $pro_id,
            'quantity'      => 1,
            'option_id'     => $option_id,
            'create_time'   => date('Y-m-d H:i:s'),
        );
        $result = $this->cart_model->add($data);
        if (!$result) exit($this->returnApiError(ApibaseController::FATAL_ERROR));

        exit($this->returnApiSuccess());
    }

    public function shop() {
        $this->cart_model->dealCart();

        if(!$this->member_info['mid']) {
            $this->error('请登录');
        }
        $cart_list = $this->cart_model
            ->alias('a')
            ->join('left join he_product as b on a.pro_id = b.pro_id')
            ->join('left join he_pro_option as c on a.option_id = c.option_id')
            ->where(['a.mid' => $this->member_info['mid']])
            ->field('a.id as cart_id, a.quantity,a.number, b.cover_photo, b.product_name, b.describe,b.if_online, c.price, c.combine_id')
            ->select();

        foreach ($cart_list as $k => $v) {
            $cart_list[$k]['detail'] = $this->attr_detail_model
                ->alias('a')
                ->join('left join he_attribute as b on a.attr_id = b.attr_id')
                ->where(['a.de_id' => ['in', $v['combine_id']]])
                ->field('a.detail_name, b.attr_name')
                ->select();
        }
//        dump($cart_list);

        $this->assign('cart_list', $cart_list);
        $this->display();
    }

    /**
     * 随机选号
     */
    public function numByChance() {
        $cart_id = I('post.cart_id');
        $cart_info = $this->cart_model->find($cart_id);

        $product_info = $this->product_model->find($cart_info['pro_id']);
        $number = $this->cart_model->getCode($cart_info['pro_id'], $product_info['total_number']);

        if($this->cart_model->where(['id' => $cart_id])->save(['number' => $number, 'number_time' => getTime()])) {
            exit($this->returnApiSuccess());
        } else {
            exit($this->returnApiError(WebbaseController::FATAL_ERROR, '选号失败，请重试'));
        }

    }

    /**
     * 删除购物车
     */
    public function delCart() {
        $cart_id = I('post.cart_id');

        if($this->cart_model->delete($cart_id)) {
            exit($this->returnApiSuccess());
        } else {
            exit($this->returnApiError(WebbaseController::FATAL_ERROR, '删除失败，请重试'));
        }
    }

    public function editCart() {
        $cart_id = I('post.cart_id');
        $number  = I('post.number');
        $cart_info = $this->cart_model->find($cart_id);

        $pro_option = $this->pro_option_model->find($cart_info['option_id']);
        if($pro_option['stock'] < $number) {
            exit($this->returnApiError(WebbaseController::FATAL_ERROR, '库存不足'));
        }
        if($this->cart_model->where(['id' => $cart_id])->save(['quantity' => $number]) == false) {
//            dump($this->cart_model->getLastSql());die;
            exit($this->returnApiError(WebbaseController::FATAL_ERROR));
        }
        exit($this->returnApiSuccess());
    }
    public function address() {
        $result = $this->address_model->where(['mid' => $this->member_info['mid']])->select();

        $this->assign('lists', $result);
        $this->assign('sale_code', I('get.sale_code'));
        $this->display();
    }

    public function addAddr() {
        $post = I('formData');
        $data = [];
        foreach ($post as $k => $v) {
            $data[$v['name']] = $v['value'];
        }
        $arr = explode('-', $data['city']);
        $data['province'] = $arr[0];
        $data['city'] = $arr[1];
        $data['country'] = $arr[2];
        $data['mid'] = $this->member_info['mid'];

        if($this->address_model->add($data)) {
            exit($this->returnApiSuccess());
        } else {
            exit($this->returnApiError(WebbaseController::FATAL_ERROR, '添加失败，请重试'));
        }
    }

    public function createOrder() {
        $addr_id = I('post.addr_id');
        $sale_code  = I('post.sale_code');

        $address_info = $this->address_model->find($addr_id);

        $cart_info = $this->cart_model->where(['mid' => $this->member_info['mid']])->select();

        $total_price = 0.00;


        foreach ($cart_info as $k => $v) {
            $product = $this->pro_option_model
                ->alias('a')
                ->join('left join he_product as b on a.pro_id = b.pro_id')
                ->where(['a.option_id' => $v['option_id']])
                ->field('a.*, b.product_name, b.freight, b.cover_photo, b.status, b.if_online')
                ->find();
//            dump($product);
            if (!$product) {
                exit($this->returnApiError(WebbaseController::FATAL_ERROR, '商品不存在'));
            }
            if($product['status'] == ProductModel::STATUS_DOWN) {
                exit($this->returnApiError(WebbaseController::FATAL_ERROR, '有商品已下架，请刷新购物车'));
            }
            if($product['stock'] < $v['quantity']) {
                exit($this->returnApiError(WebbaseController::FATAL_ERROR, '库存不足'));
            }
            if(!$v['number'] && $product['if_online'] == 'yes') {
                exit($this->returnApiError(WebbaseController::FATAL_ERROR, '请选号'));
            }

            $total_price += $product['price']*$v['quantity'];

            $product_freight[] = $product['freight'];

            $data_order_product[] = array(
                'pro_id'            => $product['pro_id'],
                'option_name'       => $product['option_name'],
                'price'             => $product['price'],
                'quantity'          => $v['quantity'],
                'cover_photo'       => setUrl($product['cover_photo']),
                'option_id'         => $product['option_id'],
                'number'            => $v['number'],
            );

        }

        $sale_info = $this->sale_member_model->where(['sale_code' => $sale_code])->find();
        if($sale_info) {
            $now_price      = sprintf('%0.2f',$total_price*$sale_info['number']/10);
            $cut_price      = $total_price-$now_price;
        } else {
            $now_price      = $total_price;
            $cut_price      = 0.00;
        }

        $freight = min($product_freight);
        $total_price += $freight;

        $order_sn = $this->order_model->getOrderNumber();

        $order = array(
            'mid'           => $this->member_info['mid'],
            'order_sn'      => $order_sn,
            'pay_type'      => OrderModel::PAY_TYPE_NO,
            'create_time'   => date('Y-m-d H:i:s'),
            'address'       => json_encode($address_info),
            'update_time'   => date('Y-m-d H:i:s'),
            'freight'       => $freight,
            'order_price'   => $now_price+$freight,
            'total_price'   => $total_price,
            'cut_price'     => $cut_price,
            'sale_code'     => $sale_code,
            'sale_number'   => $sale_info['number'],
            'status'        => OrderModel::STATUS_WAIT_FOR_PAY,
        );

        $this->order_model->startTrans();
        $is_commit = true;

        //添加订单
        $order_id = $this->order_model->add($order);
        if(!$order_id) {
            $is_commit = false;$error = 1;
        }
//        $order_product = array();
        foreach($data_order_product as $k => $v) {
            $data_order_product[$k]['order_sn'] = $order_sn;
            $data_order_product[$k]['order_id'] = $order_id;
            $data_order_product[$k]['create_time'] = getTime();
            $data_order_product[$k]['update_time'] = getTime();

        }
        //添加订单商品表
        if($this->order_product_model->addAll($data_order_product) == false) {
            $is_commit = false;$error = 2;
        }
        //删除购物车
        if($this->cart_model->where(['mid' => $this->member_info['mid']])->delete() == false) {
            $is_commit = false;
        }
//        dump($order);dump($data_order_product);die;
//        $is_commit = false;
        if($is_commit) {
            $this->order_model->commit();
            $info = array(
                'order_id'      => $order_id,
                'order_sn'      => $order_sn,
                'order_price'   => sprintf("%0.2f", $total_price),
                'freight'       => $freight,
            );
            exit($this->returnApiSuccess($info));
        } else {
            exit($this->returnApiError(WebbaseController::FATAL_ERROR, '下单失败'));
        }
    }

    public function pay() {
        $order_id = I('get.order_id');
        $order_info = $this->order_model->find($order_id);

        $this->assign($order_info);//dump($order_info);
        $this->display();
    }

    public function wxPay() {
        $order_id = I('get.order_id');
        $order_info = $this->order_model->find($order_id);
//        $order_info['order_price'] = '0.01';

        $config = C('WEIXINPAY_CONFIG');
        $order = [
            'body'         => '氦闪潮流运动',
            'total_fee'    => $order_info['order_price'] * 100,
            'out_trade_no' => $order_info['order_sn'],
            'product_id'   => $order_info['order_sn'],
            'notify_url'   => $config['NOTIFY_URL'],
        ];
//        dump($order);die;

        weixinpay($order);
    }

    public function doAlipay()
    {
//        dump($_POST);exit;
        $mid   = I('post.mid');
        $user_id = $mid;


        $order_id = I('get.order_id');
        $order_info = $this->order_model->find($order_id);
//        $order_info['order_price'] = '0.01';
        $price = $order_info['order_price'];

        $alipay_config = C('alipay_config');
        /**************************请求参数**************************/
        $payment_type = "1"; //支付类型 //必填，不能修改
        $notify_url = C('alipay.notify_url'); //服务器异步通知页面路径
        $return_url = C('alipay.return_url'); //页面跳转同步通知页面路径
        $seller_email = C('alipay.seller_email');//卖家支付宝帐户必填
//        $out_trade_no = $out_trade_no;//商户订单号 通过支付页面的表单进行传递，注意要唯一！
        $subject = "氦闪潮流运动";  //订单名称 //必填 通过支付页面的表单进行传递
        $total_fee = $price;   //付款金额  //必填 通过支付页面的表单进行传递
        $body = "氦闪潮流运动";  //订单描述 通过支付页面的表单进行传递
        $show_url = U('Index/over');  //商品展示地址 通过支付页面的表单进行传递
        $anti_phishing_key = "";//防钓鱼时间戳 //若要使用请调用类文件submit中的query_timestamp函数
        $exter_invoke_ip = get_client_ip(); //客户端的IP地址
        /************************************************************/

        //构造要请求的参数数组，无需改动
        $parameter = array(
            "service" => "create_direct_pay_by_user",
            "partner" => trim($alipay_config['partner']),
            "payment_type" => $payment_type,
            "notify_url" => $notify_url,
            "return_url" => $return_url,
            "seller_email" => $seller_email,
            "out_trade_no" => $order_info['order_sn'],
            "subject" => $subject,
            "total_fee" => $total_fee,
            "body" => $body,
            "show_url" => $show_url,
            "anti_phishing_key" => $anti_phishing_key,
            "exter_invoke_ip" => $exter_invoke_ip,
            "_input_charset" => trim(strtolower($alipay_config['input_charset']))
        );

//        dump($parameter);dump($alipay_config);exit;
        //建立请求
        vendor('Alipay_PC.Corefunction');
        vendor('Alipay_PC.Md5function');
        vendor('Alipay_PC.Notify');
        vendor('Alipay_PC.Submit');
        $alipaySubmit = new  \AlipaySubmit($alipay_config);
        $html_text = $alipaySubmit->buildRequestForm($parameter, "post", "确认");
        echo $html_text;
    }

    public function over() {
        $mid = $this->member_info['mid'];
        $order = $this->order_model->where(['mid' => $mid, 'status' => ['in', [OrderModel::STATUS_PAY_SUCCESS, OrderModel::STATUS_COMPLETE, OrderModel::STATUS_WAIT_COMMENT]]])->order('pay_time desc')->find();
        $order_product = $this->order_model
            ->alias('a')
            ->where(['a.id' => $order['id']])
            ->join('left join he_order_product as b on a.id = b.order_id')
            ->join('left join he_pro_option as c on b.option_id = c.option_id')
            ->join('left join he_product as d on b.pro_id = d.pro_id')
            ->field('a.order_price,b.quantity,  b.number,b.cover_photo,b.price, b.pro_id, c.option_name, d.product_name')
            ->order('a.pay_time desc')
            ->select();

        $this->assign('list', $order_product);
        $this->display();
    }

    /**
     * alipay 手机网站支付
     */
    public function payOrder() {
        $mid   = $this->member_info['mid'];
        $order_id = I('get.order_id');

        $order_info = $this->order_model->find($order_id);
        $out_trade_no = $order_info['order_sn'];

        $money_all = $order_info['order_price'];

        $alipay_config = C('ali_wap_pay');//dump($alipay_config);exit;
//        $alipay_config['notify_url'] = C('alipay.notify_recharge'); //服务器异步通知页面路径
//        $alipay_config['return_url'] = C('alipay.return_url_recharge'); //页面跳转同步通知页面路径
//        dump($alipay_config);die;
        vendor('AliWapPay.AlipayTradeService');
        vendor('AliWapPay.AlipayTradeWapPayContentBuilder');
        vendor('AliWapPay.AopSdk');
//        require_once dirname ( __FILE__ ).DIRECTORY_SEPARATOR.'service/AlipayTradeService.php';
//        require_once dirname ( __FILE__ ).DIRECTORY_SEPARATOR.'buildermodel/AlipayTradeWapPayContentBuilder.php';
        if ($out_trade_no){
            //商户订单号，商户网站订单系统中唯一订单号，必填
//            $out_trade_no = $_POST['WIDout_trade_no'];

            //订单名称，必填
            $subject = '氦闪潮流运动';

            //付款金额，必填
            $total_amount = $money_all;

            //商品描述，可空
            $body = '氦闪潮流运动';

            //超时时间
            $timeout_express="1m";

            $payRequestBuilder = new \AlipayTradeWapPayContentBuilder();//dump($payRequestBuilder);exit;
            $payRequestBuilder->setBody($body);
            $payRequestBuilder->setSubject($subject);
            $payRequestBuilder->setOutTradeNo($out_trade_no);
            $payRequestBuilder->setTotalAmount($total_amount);
            $payRequestBuilder->setTimeExpress($timeout_express);

            $payResponse = new \AlipayTradeService($alipay_config);
            $result=$payResponse->wapPay($payRequestBuilder,$alipay_config['return_url'],$alipay_config['notify_url']);

            return ;
        }
    }
}